package org.keshe.user;

import org.keshe.data.StuData;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public abstract class User {
    //static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";
    /**
     * 数据库相关设置
     * */
    static protected final String DB = "STUDORM";
    static protected final String DB_URL = "jdbc:mysql://localhost:3306/" + DB
            + "?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=Asia/Shanghai";
    static protected final String USER = "yang";
    static protected final String PASS = "123456";
    static protected Connection conn = null;
    static {
        try {
            DriverManager.registerDriver(new com.mysql.cj.jdbc.Driver());
        } catch (SQLException e) {
            System.err.println("驱动注册失败！");
            throw new RuntimeException(e);
        }
    }

    /**
     * 连接数据库
     * @return 返回是否连接成功
     * */
    public static boolean getConnection(){
        closeConnection();
        try {
            conn = DriverManager.getConnection(DB_URL, USER, PASS);
            // 关闭自动提交
            conn.setAutoCommit(false);
            return true;
        } catch (Exception | Error e) {
            e.printStackTrace();
            return false;
        }
    }
    /**
     * 关闭连接释放资源
     * */
    public static void closeConnection(){
        if(conn != null){
            try {
                conn.close();
            } catch (SQLException ignored) {}
        }
    }
    /**
     * 用户名
     * */
    protected String userName;
    protected User(String userName){
        this.userName = userName;
    }
    /**
     * 用户更改密码
     * @param oldVal 旧密码
     * @param newVal 新密码
     * @exception SQLException 数据库连接异常
     * @return 返回是否更改成功
     * */
    public abstract boolean changePasswd(String oldVal, String newVal) throws SQLException;


    protected static List<StuData> queryStuData(PreparedStatement preparedStatement) throws SQLException {
        ResultSet rs = preparedStatement.executeQuery();
        List<StuData> ret = new ArrayList<>();
        while (rs.next()){
            String bedName = rs.getString("BedName");
            bedName = bedName == null ? "" : bedName;
            ret.add(new StuData(rs.getString("s_id"), rs.getString("sname"),
                    rs.getString("sex"), rs.getString("major"),
                    bedName));
        }
        preparedStatement.close();
        return ret;
    }

    public String getUserName() {
        return userName;
    }
}
